'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/kh/newshd/add 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			prod_url
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		// 回调地址只能配置一个
		let numA = await vk.baseDao.selects({
			dbName: "a_newshd", // 表名
		});

		console.log("numA====", numA.total);

		if (numA.total == 1) {
			res.msgA = "添加失败"
			return res
		}


		let ma_app_id = "tt9dd0eb6d02ecbf8401"

		let A = await vk.baseDao.selects({
			dbName: "a_appid",
			// 主表where条件
			whereJson: {
				appid: ma_app_id
			},
		});

		console.log("A========", A);


		let appsecret = A.rows[0].appsecret

		let urlA = "https://open.douyin.com/oauth/client_token/"
		const accessToken = await uniCloud.httpclient.request(urlA, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
			},
			data: {
				client_key: ma_app_id, // id
				client_secret: appsecret, // 密钥
				grant_type: "client_credential",
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})

		// 有效时间为 2 个小时
		let access_token = accessToken.data.data.access_token

		// 配置回调地址
		let urlT = "https://open.douyin.com/api/industry/v1/solution/set_impl"
		const tp = await uniCloud.httpclient.request(urlT, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
				"access-token": access_token,
			},
			data: {
				operator: "后台管理员",
				release_reason: "消息回调",
				industry_impl_list: [{
					template_id: 20001,
					open_ability_impl_list: [{
						ability_identity: "/msg/playlet/review/notify",
						is_delete: false,
						test_url: prod_url.prod_url,
						prod_url: prod_url.prod_url,
						ability_type: 2,
						impl_name: "消息回调",
					}, ],
				}, ],
				app_config_item_list: [],
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})
		console.log("tp", tp);



		if (tp.data.extra.sub_description == "success") {
			res.newshd = tp.data.extra.sub_description
		}

		// 存数据库
		let dbName = "a_newshd"; // 表名
		await vk.baseDao.add({
			dbName,
			dataJson: {
				prod_url: prod_url.prod_url,
				_add_time: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
			}
		});


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}